package com.qingzhuge.serializer;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author : zero.xiao
 * @description : 对象序列化工具包
 * @date :2019-06-03 20:14
 * @modified :
 */
@Slf4j
public class SerializationUtils {
    private static Serializer serializer;
    /*
     * 初始化序列化器
     * @param ser  serialization method
     */
    static {
        serializer = new FSTSerializer();
    }

    /**
     * 针对不同类型做单独处理
     * @param obj 待序列化的对象
     * @return 返回序列化后的字节数组
     */
    public static byte[] serialize(Object obj) {
        if (obj == null) {
            return null;
        }
        byte[] bytes = new byte[0];
        try {
            bytes = serializer.serialize(obj);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    /**
     * 反序列化
     * @param bytes 待反序列化的字节数组
     * @return 序列化后的对象
     */
    public static <T> T deserialize(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        T deserialize = null;
        try {
            deserialize = serializer.deserialize(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return deserialize;
    }
}
